<?php
namespace Addons\QyWechat\Services;

use Services\Service;
use Models\BaseModel as Model;
use Session;
use Addons\QyWechat\Helper;
use EasyWeChat\Factory;

class QyWechatApi extends Service
{	
	public function get_qy_app($corp_id,$secret){
		$config = [
			'corp_id' => $corp_id,
			'secret'   => $secret,

			// 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
			'response_type' => 'array',

			'log' => [
				'level' => 'debug',
				'file' => DOXCX_FRAME_PATH . 'log/wechat.log',
			],
		];
		$app = Factory::work($config);
		return $app;
	} 
	
	public function get_qy_agent_app($corp_id,$agent_id,$secret){
		$config = [
			'corp_id' => $corp_id,
			'agent_id' => $agent_id,
			'secret'   => $secret,

			// 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
			'response_type' => 'array',

			'log' => [
				'level' => 'debug',
				'file' => DOXCX_FRAME_PATH . 'log/wechat.log',
			],
		];
		$app = Factory::work($config);
		return $app;
	}
	
	public function get_et_access_token($wid=''){
		$wid = $wid?$wid:Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $this->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		// 获取 access token 实例
		$accessToken = $etApp->access_token;
		$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		return $token;
	}
	
	//获取企业标签库
	public function get_corp_tag_list($tag_id = [],$wid=''){
		$token = $this->get_et_access_token($wid);
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?access_token=" . $token,
			json_encode([
				"tag_id" => $tag_id
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//新增渠道码
	public function add_contact_way($type,$scene,$config){
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token=" . $token,
			json_encode([
				"type" => $type,
				"scene" => $scene,
				"user" => $config['user'],
				"state" => $config['state'],
				"remark" => $config['remark'],
				"skip_verify" => $config['skip_verify']
			],320)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//修改渠道二维码
	public function update_contact_way($config_id,$config){
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/update_contact_way?access_token=" . $token,
			json_encode([
				"config_id" => $config_id,
				"user" => $config['user'],
				"remark" => $config['remark']
			],320)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//删除渠道码
	public function del_contact_way($config_id){
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_contact_way?access_token=" . $token,
			json_encode([
				"config_id" => $config_id
			],320)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//新增标签
	public function add_corp_tag($param){
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag?access_token=" . $token,
			json_encode([
				"group_id" => $param['group_id'],
				"group_name" => $param['group_name'],
				"tag" => $param['tag']
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//删除标签
	public function del_corp_tag($param){
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag?access_token=" . $token,
			json_encode([
				"tag_id" => $param['tag_id'],
				"group_id" => $param['group_id'],
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//编辑企业客户标签
	public function edit_corp_tag($param){
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_corp_tag?access_token=" . $token,
			json_encode([
				"id" => $param['id'],
				"name" => $param['name'],
				//"order" => $param['order']
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//编辑客户企业标签
	public function edit_et_tag($param,$wid=''){
		$token = $this->get_et_access_token($wid);
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag?access_token=" . $token,
			json_encode([
				"userid" => $param['userid'],
				"external_userid" => $param['external_userid'],
				"add_tag" => $param['add_tag'],
				"remove_tag" => $param['remove_tag']
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//获取群列表
	// public function get_et_groupchat_list(){
	// 	$token = $this->get_et_access_token();
	// 	$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=" . $token,
	// 		json_encode([
	// 			"offset" => 0,
	// 			"limit" => 1000,
	// 		])
	// 	);
	// 	$resp_arr = json_decode($body, 1);
	// 	return $resp_arr;
	// }
	//获取群列表
	public function get_et_groupchat_list(){
		$data = [
			"limit" => 1000,
		];
		$result = [];
		$res = true;
		$token = $this->get_et_access_token();
		while ($res) {
			$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=" . $token,
				json_encode($data)
			);
			$resp_arr = json_decode($body, 1);
			$result = array_merge($result , $resp_arr['group_chat_list']);
			if($resp_arr['errcode'] == 0 && $resp_arr['next_cursor'] != ''){
				$data['cursor'] = $resp_arr['next_cursor'];
			}else{
				$res = false;
			}
		}
		return $result;
	}
	
	//获取群详情
	public function get_et_groupchat_info($chat_id,$wid=''){
		$token = $this->get_et_access_token($wid);
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=" . $token,
			json_encode([
				"chat_id" => $chat_id,
				"need_name" => 1,
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//获取客户群统计数据
	public function get_et_groupchat_statistic($begin_time = ''){
		if(!$begin_time){
			$begin_time = strtotime("-1 day");
		}
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic?access_token=" . $token,
			json_encode([
				"day_begin_time" => $begin_time,
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//添加群欢迎语素材
	public function add_group_welcome_template($param = []){
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/add?access_token=" . $token,
			json_encode($param)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//编辑群欢迎语素材
	public function edit_group_welcome_template($param = []){
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/edit?access_token=" . $token,
			json_encode($param)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//删除群欢迎语素材
	public function del_group_welcome_template($template_id){
		$token = $this->get_et_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/del?access_token=" . $token,
			json_encode([
				'template_id'=>$template_id
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//修改客户备注信息
	public function edit_et_remark($param,$wid=''){
		$token = $this->get_et_access_token($wid);
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark?access_token=" . $token,
			json_encode([
				"userid" => $param['userid'],
				"external_userid" => $param['external_userid'],
				"remark" => $param['remark']
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//修改客户备注信息
	public function edit_et_remark_description($param,$wid=''){
		$token = $this->get_et_access_token($wid);
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark?access_token=" . $token,
			json_encode([
				"userid" => $param['userid'],
				"external_userid" => $param['external_userid'],
				"description" => $param['description']
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//批量获取客户详情
	public function get_moment_list($wid){
		$time = time();
        $ktime = $time-3600*24*30;
        $res = true;
        $datas = [];
        $data = array("start_time"=>$ktime,"end_time"=>$time);
		$result = [];
		$res = true;
		$token = $this->get_et_access_token($wid);
		while ($res) {
			$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_list?access_token=" . $token,
				json_encode($data)
			);
			$resp_arr = json_decode($body, 1);
			$result = array_merge($result , $resp_arr['moment_list']);
			if($resp_arr['errcode'] == 0 && $resp_arr['next_cursor'] != ''){
				$data['cursor'] = $resp_arr['next_cursor'];
			}else{
				$res = false;
			}
		}
		return $result;
	}
	
	public function get_moment_comments($wid,$moment_id,$userid){
		$token = $this->get_et_access_token($wid);
	    $like_arr = array("access_token"=>$token,"moment_id"=>$moment_id,"userid"=>$userid);
        $like_url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_comments?access_token=".$token;
        $body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_comments?access_token=" . $token,
			json_encode($like_arr)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//批量获取客户详情
	public function get_et_list($userid,$wid){
		$data = [
			'userid' => $userid,
			"limit" => 100,
		];
		$result = [];
		$res = true;
		$token = $this->get_et_access_token($wid);
		while ($res) {
			$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token=" . $token,
				json_encode($data)
			);
			$resp_arr = json_decode($body, 1);
			$result = array_merge($result , $resp_arr['external_contact_list']);
			if($resp_arr['errcode'] == 0 && $resp_arr['next_cursor'] != ''){
				$data['cursor'] = $resp_arr['next_cursor'];
			}else{
				$res = false;
			}
		}
		return $result;
	}

	//下载图片到本地获取media_id
	public function get_media_id($wid,$image=""){
		$wid = $wid?$wid:Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $this->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$len = strlen($str)-1;
 		$randstr = '';
 		for ($i=0;$i<6;$i++) {
	  		$num=mt_rand(0,$len);
	 	 	$randstr .= $str[$num];
 		}
 		$save_file = $randstr.".png";
		file_put_contents($save_file, file_get_contents($image));
		$data = $etApp->media->uploadImage($save_file)["media_id"];
		unlink($save_file);
		return $data;
	}
 
	//企业魔盒发送图片消息
	public function send_img($userid,$image,$wid=''){
		$wid = $wid?$wid:Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
		$app = $this->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
		$accessToken = $app->access_token;
		$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		$etApp = $this->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$media_id = $etApp->media->uploadImage($image)["media_id"];
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$token,
			json_encode([
				"touser" => $userid,
				"msgtype" => 'image',
				"agentid" => $sendConfig->agent_id,
				"image"=>[
					"media_id" => $media_id
				]
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//企业魔盒发送图文消息
	public function send_link($userid,$data,$wid=''){
		$wid = $wid?$wid:Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
		$app = $this->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
		$accessToken = $app->access_token;
		$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$token,
			json_encode([
				"touser" => $userid,
				"msgtype" => 'news',
				"agentid" => $sendConfig->agent_id,
				"news"=>[
					"articles" =>$data
				]
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//企业魔盒发视频消息
	public function send_video($userid,$agentid,$video,$wid=''){
		$wid = $wid?$wid:Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
		$app = $this->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
		$accessToken = $app->access_token;
		$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $this->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$media_id = $etApp->media->uploadVideo($video)["media_id"];
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$token,
			json_encode([
				"touser" => $userid,
				"msgtype" => 'video',
				"agentid" => $agentid,
				"video"=>[
					"media_id" => $media_id
				]
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	public function send_text($userid,$agentid,$wid='',$title,$description,$url){
		$wid = $wid?$wid:Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
		$app = $this->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
		$accessToken = $app->access_token;
		$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		$etApp = $this->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$token,
			json_encode([
				"touser" => $userid,
				"msgtype" => 'textcard',
				"agentid" => $agentid,
				"textcard"=>[
					"title" => $title,
					"description" => $description,
					"url" => $url,
				]
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	public function send_text_wen($userid,$agentid,$wid='',$content){
		$wid = $wid?$wid:Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
		$app = $this->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
		$accessToken = $app->access_token;
		$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		$etApp = $this->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$token,
			json_encode([
				"touser" => $userid,
				"msgtype" => 'text',
				"agentid" => $agentid,
				"text"=>[
					"content" => $content
				]
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	//获取客户信息
	public function get_info($wid='',$external_userid){
		$wid = $wid?$wid:Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$replyConfig = Helper::getInstance()->get_message_send_config($wid);
		$app = $this->get_qy_agent_app($qyConfig->corp_id,$replyConfig->agent_id,$replyConfig->secret);
		$accessToken = $app->access_token;
		$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		$urls = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token='.$token.'&external_userid='.$external_userid;
		$resArr = json_decode(curlGet($urls),1);
		return $resArr;
	}

	// public function get_infos($wid='',$external_userid){
	// 	$wid = $wid?$wid:Session::get('wid');
	// 	$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
	// 	$replyConfig = Helper::getInstance()->get_message_send_config($wid);
	// 	$app = $this->get_qy_agent_app($qyConfig->corp_id,$replyConfig->agent_id,$replyConfig->secret);
	// 	$accessToken = $app->access_token;
	// 	$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
	// 	$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/convert_to_openid?access_token=".$token,
	// 		json_encode([
	// 			"external_userid" => $external_userid
	// 		])
	// 	);
	// 	return $body;
	// }
}
